package org.yylnb.openplatform.gateway.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.yylnb.openplatform.commons.constans.ApiTagInRedis;
import org.yylnb.openplatform.commons.utlis.CommonsResult;
import org.yylnb.openplatform.gateway.api.CacheService;
import org.yylnb.openplatform.gateway.utils.Md5Utils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.Map;
import java.util.TreeMap;

/**
 * 当前过滤器主要作用是判断用户的请求参数是否被修改,通过校验签名的方式
 *
 * @author RainLin
 * @date 2020/7/25 - 20:09
 */
@Component
public class SignFilter extends ZuulFilter {


    private static final Logger LOGGER = LoggerFactory.getLogger(SignFilter.class);

    private final CacheService cacheService;
    private final ObjectMapper objectMapper;


    public SignFilter(CacheService cacheService, ObjectMapper objectMapper) {
        this.cacheService = cacheService;
        this.objectMapper = objectMapper;
    }

    @Override
    public String filterType() {
        //前置过滤器
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 85;
    }

    @Override
    public boolean shouldFilter() {
        return false;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext context = RequestContext.getCurrentContext();
        //获取到用户传递的参数
        HttpServletRequest request = context.getRequest();
        //获取需要校验的参数,并且自动排序
        Map<String, String> signMap = new TreeMap<>();
        //用户传递的参数中除了签名之外的参数都放到上面map中
        Enumeration<String> parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String param = parameterNames.nextElement();
            if ("sign".equalsIgnoreCase(param)) {
                continue;
            }
            signMap.put(param, request.getParameter(param));
        }

        //获取用户的密码(盐),理论上应该是根据当前使用的app_key,因为一个用户会有多个app,每个应该都有不一样的盐
        //我们通过要求用户传递一个app_key的参数来告诉我们它是谁,然后我们根据这个key去查找它的密码
        Map<String, String> resultMap = null;
        resultMap = cacheService.hGet(ApiTagInRedis.API_SYSTEM_PARAMETER + request.getParameter("app_key"), "appSecret").getData();

        //密码
        String appSecret = resultMap.get("data");

        //按照我们的签名规则,生成新的签名
        //计算出来用户传递的数据应该传递的签名是什么
        String md5Signature = Md5Utils.md5Signature(signMap, appSecret);
        //获取到用户传递的签名,和我们计算出来的签名进行比较
        //用户传递的签名
        String sign = request.getParameter("sign");
        LOGGER.error("应该传递的签名是:{}" + "    ====>传递的签名是:{}", md5Signature, sign);

        if (!md5Signature.equalsIgnoreCase(sign)) {
            //两个签名不一样,需要拦截请求
            context.setSendZuulResponse(false);
            HttpServletResponse response = context.getResponse();
            response.setContentType("application/json;charset=utf-8");
            try {
                context.setResponseBody(objectMapper.writeValueAsString(CommonsResult.ERROR.msg("签名校验失败")));
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            return null;
        }

        //保存签名,用于后面的幂等性操作使用
        context.put("sign", sign);
        return null;
    }
}
